package com.imooc.ecommerce.config;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 通过Nacos 下发动态路由配置，监听nacos中路由配置的变更
 * DependsOn是强调依赖类GatewayConfig Bean先注入，在注册该类
 * @author zhangshao
 * @since 2023/11/24 21:00
 */
@Slf4j
@Component
@DependsOn("gatewayConfig")
public class DynamicRouteServiceImplByNacos {

    /**
     * Nacos配置服务客户端
     */
    private ConfigService configService;

    private final DynamicRouteServiceImpl dynamicRouteService;


    public DynamicRouteServiceImplByNacos(DynamicRouteServiceImpl dynamicRouteService) {
        this.dynamicRouteService = dynamicRouteService;
    }

    /**
     * 初始化 Nacos Config,填充 Nacos配置中心信息
     *
     */
    private ConfigService initConfigService() {

        try {
            Properties properties = new Properties();
            properties.setProperty("serverAddr", GatewayConfig.NACOS_SERVER_ADD);
            properties.setProperty("namespace", GatewayConfig.NACOS_NAMESPACE);
            return configService = NacosFactory.createConfigService(properties);
        } catch (NacosException ex) {
            log.error("init gateway nacos config error :[{}]", ex.getMessage(), ex);
            return null;
        }
    }

    /**
     * 监听 nacos下发的动态路由配置信息
     *
     * @param dataId nacos dataId
     * @param group nacos Group
     */
    private void dynamicRouteByNacosListener(String dataId, String group) {

        try {
            // 给nacos config客户端增加一个监听器
            configService.addListener(dataId, group, new Listener() {

                /**
                 * 自己提供线程池执行操作
                 */
                @Override
                public Executor getExecutor() {
                    return null;
                }

                /**
                 * 监听器收到配置更新
                 * @param configInfo Nacos中最新的配置定义
                 */
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("start to update config :[{}]", configInfo);
                    List<RouteDefinition> definitionList = JSON.parseArray(configInfo, RouteDefinition.class);
                    log.info("update route :[{}]", definitionList.toString());

                    dynamicRouteService.updateList(definitionList);
                }
            });
        } catch (NacosException ex) {
            log.error("dynamic update gateway config error :[{}]", ex.getMessage(), ex);
        }
    }

    /**
     * Bean在容器中构造完成之后会执行 init 方法，读取初始化Nacos配置中心内容
     */
    @PostConstruct
    public void init() {
        log.info("gateway route init...");
        try {
            // 初始化 Nacos 配置客户端
            configService = initConfigService();
            if (null == configService) {
                log.error("init config service fail");
                return;
            }

            // 通过Nacos Config 并指定路由配置路径去获取路由配置
            String configInfo = configService.getConfig(
                    GatewayConfig.NACOS_ROUTE_DATA_ID,
                    GatewayConfig.NACOS_ROUTE_GROUP,
                    GatewayConfig.DEFAULT_TIMEOUT
            );

            log.info("get current gateway config:[{}]", configInfo);
            List<RouteDefinition> definitionList = JSON.parseArray(configInfo, RouteDefinition.class);
            if (CollectionUtil.isNotEmpty(definitionList)) {
                for (RouteDefinition definition : definitionList) {
                    log.info("init gateway config :[{}]", definition.toString());
                    dynamicRouteService.addRouteDefination(definition);
                }
            }


        } catch (Exception ex) {
            log.error("gateway route init has some error :[{}]", ex.getMessage(), ex);
        }

        // 设置监听器
        dynamicRouteByNacosListener(GatewayConfig.NACOS_ROUTE_DATA_ID, GatewayConfig.NACOS_ROUTE_GROUP);
    }

}
